package com.sali.b_design_pattern.g_singleton_pattern.lesson_singleton.b_lazy.b_thread_safe.cas;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @description:
 * @date: 2023/3/19 13:44.
 * @version: 1.0
 */
public class CasSingleton {

    /**
     * description: 构造函数私有化
     **/
    private CasSingleton() {
    }

    /**
     * description: 使用AtomReference定义原子对象
     **/
    private static final AtomicReference<CasSingleton> instance = new AtomicReference<>();

    /**
     * description: 使用自旋的方式进行处理
     **/
    public static final CasSingleton getInstance() {
        for (; ; ) {
            CasSingleton casSingleton = instance.get();
            if (casSingleton != null) {
                return casSingleton;
            }

            // 如果不存在，就开始创建一个对象和null进行比较和交换
            instance.compareAndSet(null, new CasSingleton());
            // 返回实例
            return instance.get();
        }
    }

}
